package com.sxkiler.demo.seata.service;

import com.sxkiler.demo.seata.dao.XAOrderDao;
import com.sxkiler.demo.seata.dto.OrderDTO;
import com.sxkiler.demo.seata.service.xa.XAAccountService;
import com.sxkiler.demo.seata.service.xa.XAOrderService;
import io.seata.core.context.RootContext;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@org.apache.dubbo.config.annotation.Service
@Service
public class XAOrderServiceImpl implements XAOrderService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private XAOrderDao orderDao;

    @Reference
    private XAAccountService accountService;

    @Override
    public boolean createOrder(OrderDTO orderDTO) throws Exception {
        logger.info("[createOrder] 当前 XID: {}", RootContext.getXID());

        // 扣减余额
        boolean reduceBalance = accountService.reduceBalance(orderDTO.getUserId(), orderDTO.getPayAmount());

        if(!reduceBalance){
            throw new RuntimeException("扣减余额失败");
        }

        // 保存订单
        logger.info("[createOrder] 开始创建订单: {}", orderDTO.toString());
        int saveOrder = orderDao.saveOrder(orderDTO);
        if(saveOrder == 0){
            logger.warn("[createOrder] 创建订单 {} 失败", orderDTO.toString());
            throw new Exception("创建订单失败");
        }
        logger.info("[createOrder] 保存订单: {}", orderDTO.getId());

        return true;
    }

}
